import { ApiConfig } from 'ApiConfig.js';

class Token
{
  constructor(){
    this.verifyUrl = ApiConfig.restUrl + 'api/token/verify';
    this.tokenUrl = ApiConfig.restUrl + 'api/token/create';
  }

  verify() {
    var token = wx.getStorageSync('token');
    if (!token) {
      this.getTokenFromServer();
    }else {
      this._veirfyFromServer(token);
    }
  }
   // 携带令牌去服务器校验令牌
   _veirfyFromServer(token) {
    var that = this;
    wx.request({
      url: that.verifyUrl,
      method: 'POST',
      data: {
        token: token
      },
      success: function (res) {
        var valid = res.data.isValid;
        if (!valid) {
          that.getTokenFromServer();
        }
      }
    })
  }

  //从服务器获取token
  getTokenFromServer(callBack) {
    var that = this;
    //解决异步请求token
    return new Promise(function(resolve, reject){
      if(wx.getStorageSync('token')){
            resolve(wx.getStorageSync('token'))
          }else{
            wx.login({
              success: function (res) {
                wx.request({
                  url: that.tokenUrl,
                  method: 'POST',
                  data: {
                    code: res.code
                  },
                  success: function (res) {
                    console.log(res.data);
                    wx.setStorageSync('token', res.data.token);
                    callBack && callBack(res.data.token);
                  }
                })
              }
            })
          }
      })
  }
}

export { Token };